package com.sihan.swvp.listener;


import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sihan.swvp.entity.sys.User;
import com.sihan.swvp.service.sys.UserService;



public class SessionListener implements HttpSessionListener{

  
    // session创建时调用这个方法  
    @Override  
    public void sessionCreated(HttpSessionEvent se) { 
    	
    }  
  
    // Session失效或者过期的时候调用的这个方法,  
    @Override  
    public void sessionDestroyed(HttpSessionEvent se) {  
        try {  
        	HttpSession session=se.getSession();
            User u = (User) se.getSession().getAttribute("u"); 
            String account = u.getAccount();
            long id = u.getId();
            UserService userService=(UserService)this.getObjectFromApplication(session.getServletContext(), "userService");  
            userService.setConnById(id, 0);
        } catch (Exception e) {  
        	e.printStackTrace();
        }  
    }
    private Object getObjectFromApplication(ServletContext servletContext,String beanName){  
        //通过WebApplicationContextUtils 得到Spring容器的实例。  
        ApplicationContext application=WebApplicationContextUtils.getWebApplicationContext(servletContext);  
        //返回Bean的实例。  
        return application.getBean(beanName);  
    } 

}
